import json
import os

import jinja2


def GetFileFromThisRootDir(argPath, ext=None):
    allfiles = []
    needExtFilter = (ext is not None)
    for files in os.listdir(argPath):
        # rec_filepath = os.path.join(root, filesPath)
        rec_filepath = os.path.join(argPath, files)
        # rec_filepath = filesPath
        extension = os.path.splitext(rec_filepath)[1][1:]
        if needExtFilter and extension in ext:
            allfiles.append(rec_filepath)
        elif not needExtFilter:
            allfiles.append(rec_filepath)
    return allfiles


JsonName = "define_file"
load_f_object = open(JsonName + ".json", 'rt', encoding='utf-8')
load_f_contents = load_f_object
data_json = json.load(load_f_contents)
print(data_json)
ModelName = "messagetypes_h"
env = jinja2.Environment(loader=jinja2.FileSystemLoader(''))
# print(env.get_template('model_cpp.tmpl').render(model))

for tmplFileName in GetFileFromThisRootDir(os.path.join(os.getcwd(), 'tmpl'), ['tmpl']):
    outputCodeFile = tmplFileName[:-5]
    outputCodeFile = outputCodeFile.replace('_', '.')
    outputCodeFile = os.path.basename(outputCodeFile)
    outputCodeFile = os.path.join(os.path.join(os.getcwd(), 'outputCode'), outputCodeFile)
    output = open(outputCodeFile, 'w', encoding='utf-8')
    env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(tmplFileName)))
    output.write(env.get_template(os.path.basename(tmplFileName)).render(data_json))
    output.close()
    print('tmplFileName:' + tmplFileName)
    print('outputCodeFile:' + outputCodeFile)
